package com.kucun.service.imp;

import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kucun.Dao.BilldetailMapper;
import com.kucun.Dao.BillmasterMapper;
import com.kucun.Dao.GoodsMapper;
import com.kucun.bean.Billmaster;
import com.kucun.bean.Goods;
import com.kucun.bean.Page;
import com.kucun.bean.Billdetail;
import com.kucun.bean.Users;
import com.kucun.controller.BilldetailController;
import com.kucun.service.Billdetailservice;
import com.kucun.util.BeanUtilsExtends;
import com.times.util.DateUtils;
@Service
@Transactional(rollbackFor=Exception.class)
public class Billdetailserviceimp implements Billdetailservice {
	private static final Logger logger = Logger.getLogger(Billdetailserviceimp.class.getName());
	@Resource
	private BilldetailMapper billdetailMapper;
	@Resource
	private BillmasterMapper billmasterMapper;
	@Resource
	private GoodsMapper goodsMapper;
	
	public boolean save(Billdetail billdetail) {
		return billdetailMapper.insert(billdetail);
	}

	public boolean update(Billdetail billdetail) {
		return billdetailMapper.updateByPrimaryKey(billdetail);
	}

	public boolean delete(String id) {
		return billdetailMapper.delete(id);
	}


	public Billdetail findById(int userid) {
		return billdetailMapper.selectByPrimaryKey(userid);
	}


	public List<Billdetail> findAll(Page page) {
		return (List<Billdetail>)billdetailMapper.findAll(page);
	}

	

	public Page getCount(String cs,String type) {
		
		return billdetailMapper.getCount(cs,type);
	}

	
	public List<Billdetail> query(Billdetail billmaster,int i,int rows) {
		return (List<Billdetail>)billdetailMapper.query(billmaster,i,rows);
	}

	public Page queryCount(Billdetail billmaster) {
		return billdetailMapper.queryCount(billmaster);
	}

	public Object Savebilldate(HttpServletRequest request) throws Exception  {
		Object s=null; 
		Users user=(Users)request.getSession().getAttribute("user");
		
		String remark=request.getParameter("remark");	
		String billtype=request.getParameter("billtype");	
		String myrows = request.getParameter("rows");
	
		if(!"".equals(remark)){
			remark=URLDecoder.decode(remark, "UTF-8");
		}
		if(!"".equals(billtype)){
			billtype=URLDecoder.decode(billtype, "UTF-8");
		}
		if(!"".equals(myrows)){
			myrows = URLDecoder.decode(myrows, "UTF-8");
		}
		String billno="";
		
	
		Map map=new HashMap();
		map.put("digit", 8);
		map.put("orderNo", "");
		if(billtype.equals("入库单")){
			map.put("prefix", "KC");
			// billno="KC"+DateUtils.getStringDateShort1()+(billmasterMapper.getmaxid(billtype).getTotal()+1);
			 billno=billmasterMapper.generate_orderNo(map);
		}else if(billtype.equals("出库单")){
			map.put("prefix", "CK");
			//billno="CKD"+DateUtils.getStringDateShort1()+(billmasterMapper.getmaxid(billtype).getTotal()+1);
			//String prefix,int digit,String orderNo
			 billno=billmasterMapper.generate_orderNo(map);
		}

		
	  	//保存主表数据
	  	Billmaster bi=new Billmaster();
	  	bi.setBillno(billno);
	  	bi.setRemark(remark);
	  	bi.setBilddate(new Date());
	  	bi.setBilltype(billtype); //单据类型
	  	bi.setCreateid(user.getUserid());
	  	bi.setCreatename(user.getLogname());
	  	bi.setStates("草稿");
	  	bi.setIsdelet(0);
	  	int biid=billmasterMapper.insertBillmaster(bi);
	  	//System.out.println("主表数据返回id="+bi.getId());
		if(biid>0){
			//将得到的子表数据原为json格式的字符串转成JSONArray并取值
		  	net.sf.json.JSONArray jsarr=new net.sf.json.JSONArray();
		  	jsarr=net.sf.json.JSONArray.fromObject(myrows);
		  	for (Object object : jsarr) {
		  		net.sf.json.JSONObject obj= (net.sf.json.JSONObject) object;
		  		Billdetail bill=new Billdetail();
		  		//复制对象
				BeanUtils.copyProperties(bill,obj);
				if("请必选".equals(bill.getClientname())){
					continue;
				}
		  		bill.setBilltype(billtype);
		  		if("出库单".equals(billtype)){  //如何是出库单需要保存领用人和领用时间
		  			bill.setLeadingperson(user.getLogname());
		  			bill.setLeadingtime(new Date());  
		  		}else{  
                    bill.setLeadingperson(user.getLogname());
		  			bill.setLeadingtime(new Date());
		  			bill.setBeiyon(billno);
		  		}

		  		bill.setParentid(bi.getId());
		  		bill.setCreatedate(new Date());
		  		s=billdetailMapper.insertSelective(bill);
		  		//System.out.println("对象复制="+bill.getClientname() +"=="+bill.getGoodname());
		  	  }
		  	}
		return s;
	}


	public List<Billdetail> querybilldatebyParentid(Billdetail map) {
		return billdetailMapper.querybilldatebyParentid(map);
	}
    /******单子明细数据保存*******/
	public Object updatebilldate(HttpServletRequest request) throws Exception {
		Object s=null; 
		Users user=(Users)request.getSession().getAttribute("user");
		String remark=request.getParameter("remark");	
		String billtype=request.getParameter("billtype");	
		String billno=request.getParameter("billno"); //库存编码
		String id=request.getParameter("id");	 //主表id
		String myrows = request.getParameter("rows");
		if(!"".equals(remark)){
			remark=URLDecoder.decode(remark, "UTF-8");
		}
		if(!"".equals(billtype)){
			billtype=URLDecoder.decode(billtype, "UTF-8");
		}
		if(!"".equals(myrows)){
			myrows = URLDecoder.decode(myrows, "UTF-8");
		}	
	  	//保存主表数据
	  	Billmaster bi=new Billmaster();
	  	bi.setRemark(remark);
	  	bi.setId(Integer.valueOf(id));
	  	bi.setAsd(user.getUsername()+"变跟当前数据；时间"+DateUtils.getStringDate());
	  	int biid=billmasterMapper.updateByPrimaryKeySelective(bi);
	  	System.out.println("主表数据返回id="+biid);
		if(biid>0){
			//将得到的子表数据原为json格式的字符串转成JSONArray并取值
		  	net.sf.json.JSONArray jsarr=new net.sf.json.JSONArray();
		  	jsarr=net.sf.json.JSONArray.fromObject(myrows);		  	
		  	for (Object object : jsarr) {
		  		net.sf.json.JSONObject obj= (net.sf.json.JSONObject) object;
		  		Billdetail bill=new Billdetail();
		  		//复制对象
		  		BeanUtilsExtends.copyProperties(bill,obj);
				if("请必选".equals(bill.getClientname())){  //如果没双击操作就不保存此数据到数据库中
					continue;
				}
			    if(bill.getId()!=null){  //如果id为空就新增明细，如果 id不为空就保存明细
			    	s=billdetailMapper.updateByPrimaryKeySelective(bill);
			    }else{
			    	bill.setBeiyon(billno);
			  		bill.setBilltype(billtype);
			  		bill.setParentid(bi.getId());
			  		bill.setCreatedate(new Date());
			  		bill.setLeadingperson(user.getLogname());
			  		bill.setLeadingtime(new Date());
			    	s=billdetailMapper.insertSelective(bill);
			    }
		  		//System.out.println("对象复制="+bill.getClientname() +"=="+bill.getGoodname());
		  	  }
		  	}
		return s;
	}

	public int deleteByPrimaryKey(Integer id) {
		return billdetailMapper.deleteByPrimaryKey(id);
	}
     /********删除主数据，明细数据；实际删除**********/
	public Object updatebilldateToDel(String ids)throws Exception {	
		boolean s=billmasterMapper.delete(ids);
		boolean s1=false;
		if(s){
			s1=billdetailMapper.updatebilldateToDel(ids);
		}
		if(s1)
		logger.error("删除表[billdetail;billmaster]的数据成功；数据ids【"+ids+"】");
		
		return s1;
	}
    /*******提交入库单数据*********/
	public boolean updatebilldateToSubmit(String ids) throws Exception {
		boolean s1=false;
		int s=billmasterMapper.updateBillmasterToSubmit(ids);
		if(s>0){
			//先修改出库单的明细数据的状态为已完成
			s1=billdetailMapper.updatebilldateToSubmit(ids);
			//然后修改入库单的对应的明细数据上的stockrate（库存量）
			s1=billdetailMapper.updatebilldateToStockrate(ids);
			
		}
		return s1;
	}
    /***
     * 出库单提交时需要验证库存是否充足
     */
	public List<Billdetail> VerifyInventory(String ids) {
		return billdetailMapper.VerifyinventoryDate(ids);
	}

	public List<Billdetail> GetGoodsExistOut(Page page) {
		
		return billdetailMapper.GetGoodsExistOut(page);
	}

	public Page GetGoodsExistOutCount(Page page) {
		return billdetailMapper.GetGoodsExistOutCount(page);
	}

	public List<Billdetail> QueryBillDateByParentIDS(String ids) {
		return billdetailMapper.QueryBillDateByParentIDS(ids);
	}
  /**入库单提交完成*/
	public boolean updatebilldateToSubmitOfInCome(String ids) throws Exception {
		boolean s1=false;
		int s=billmasterMapper.updateBillmasterToSubmitOfInCome(ids);
		if(s>0){
			s1=billdetailMapper.updatebilldateToSubmitOfInCome(ids);
		}
		return s1;
	}
	
}
